<script setup lang="tsx">
import { defineExpose, inject, nextTick, ref, watch } from 'vue';
import type { TreeProps } from 'ant-design-vue';
import { ElTree } from 'element-plus';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { getRoyiDepTree, royuDataScope } from '@/service/api';
import '/node_modules/element-plus/dist/index.css';

export type OperateType = AntDesign.TableOperateType;
interface Props {
  rowData: any;
}

interface Model {
  roleName: any;
  roleKey: any;
  dataScope: any;
}
const refreshList = inject('refreshList');

type RuleKey = Extract<keyof Model, 'roleName' | 'roleKey'>;
const props = defineProps<Props>();
const { createRequiredRule } = useFormRules();
const rules: Record<RuleKey, App.Global.FormRule> = {
  roleName: createRequiredRule('角色名称不能为空'),
  roleKey: createRequiredRule('权限字符不能为空')
};

const { formRef, validate, resetFields } = useAntdForm();
const model = ref<Model>(getMode());

function getMode(): Model {
  return {
    roleName: null,
    roleKey: null,
    dataScope: '1'
  };
}

const dataScopeOptions = ref([
  {
    value: '1',
    label: '全部数据权限'
  },
  {
    value: '2',
    label: '自定数据权限'
  },
  {
    value: '3',
    label: '本部门数据权限'
  },
  {
    value: '4',
    label: '本部门及以下数据权限'
  },
  {
    value: '5',
    label: '仅本人数据权限'
  }
]);
const treeRef = ref(null);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const treeData = ref<TreeProps['treeData']>([]);
const defaultProps = {
  children: 'children',
  label: 'label'
};
function handleCheckedTreeExpand(val) {
  for (let i = 0; i < treeData.value.length; i++) {
    treeRef.value.store.nodesMap[treeData.value[i].id].expanded = val.target.checked;
  }
}

function handleCheckedTreeNodeAll(val) {
  treeRef.value.setCheckedNodes(val.target.checked ? treeData.value : []);
}

function handleCheckedTreeConnect(val) {
  model.value.menuCheckStrictly = Boolean(val.target.checked);
  console.log('model.value.menuCheckStrictly :>> ', model.value.menuCheckStrictly);
}

function getAllCheckedKeys() {
  // 添加检查确保 treeRef 存在再调用其方法
  if (!treeRef.value) {
    return [];
  }

  const checkedKeys = treeRef.value.getCheckedKeys();
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

function resetForm() {
  resetFields();
}

function getData() {
  getRoyiDepTree(props.rowData.roleId).then( res => {
    console.log('res :>> ', res);
      const data = res.otherData
      if (data && data.code == 200) {
        treeData.value = data.depts;
        // 添加检查确保 checkedKeys 存在且为数组
        const checkedKeys = data.checkedKeys;
        if (checkedKeys && Array.isArray(checkedKeys) && checkedKeys.length > 0) {
          checkedKeys.forEach((v: any) => {
            nextTick(() => {
              treeRef.value && treeRef.value.setChecked(v, true, false);
            });
          });
        }
      }
  });
}

function handleDataScopeChange() {
  treeRef.value?.setCheckedNodes && treeRef.value?.setCheckedNodes([]);
}

function submitForm() {
  let deptIds: any[] = [];
  if (model.value.dataScope == 2) {
    deptIds = getAllCheckedKeys();
  }
  const params: any = {
    ...props.rowData,
    ...model.value,
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    deptIds
  };
  royuDataScope(params).then(({ data, error }) => {
    if (!error) {
      window.$message?.success('操作成功');
      refreshList(true, 2);
    }
  });
}
watch(
  () => props.rowData,
  val => {
    if (val) {
      model.value = {
        roleName: val.roleName,
        roleKey: val.roleKey,
        dataScope: val.dataScope
      };
      getData();
    }
  },
  {
    immediate: true,
    deep: true
  }
);

defineExpose({
  resetForm,
  submitForm,
  handleDataScopeChange
});
</script>

<template>
  <AForm ref="formRef" :model="model" :rules="rules" :label-col="{ lg: 8, xs: 4 }" label-wrap>
    <ARow :gutter="20">
      <ACol :lg="24" :xs="24">
        <AFormItem name="roleName" label="角色名称" :label-col="{}">
          <AInput v-model:value="model.roleName" placeholder="请输入角色名称" autocomplete="off" disabled />
        </AFormItem>
      </ACol>
      <ACol :lg="24" :xs="24">
        <AFormItem name="roleKey" :label-col="{}">
          <template #label>权限字符</template>
          <AInput v-model:value="model.roleKey" placeholder="请输入角色名称" autocomplete="off" disabled />
        </AFormItem>
      </ACol>
      <ACol :lg="24" :xs="24">
        <AFormItem name="dataScope" label="权限范围" :label-col="{}">
          <ASelect v-model:value="model.dataScope" placeholder="请输入权限范围" @change="handleDataScopeChange">
            <ASelectOption v-for="item in dataScopeOptions" :key="item.value" :value="item.value">
              {{ item.label }}
            </ASelectOption>
          </ASelect>
        </AFormItem>
      </ACol>
      <ACol v-if="model.dataScope == 2" :lg="24" :xs="24">
        <div class="lable w-full font-size-14px">数据权限:</div>
        <ACheckbox v-model:checked="menuExpand" class="mt-5px" @change="handleCheckedTreeExpand($event)">
          展开/折叠
        </ACheckbox>
        <ACheckbox v-model:checked="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</ACheckbox>
        <div class="tree mt-8px max-h-200px w-full overflow-auto border-b-black">
          <ElTree
            ref="treeRef"
            class="menu-tree"
            :check-strictly="model.deptCheckStrictly"
            :data="treeData"
            show-checkbox
            default-expand-all
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </div>
      </ACol>
    </ARow>
  </AForm>
</template>

<style lang="scss"></style>
